<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'taskInstanceStatus'">
        {{ taskStatusMap[record.taskInstanceStatus as keyof typeof taskStatusMap]?.text || '--' }}
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="goToDetaile(record)">详情</a>
          <a @click="rollbackDeployment(record)" v-if="record.taskInstanceStatus == TaskStatus.success">回滚</a>
        </div>
      </template>
    </template>
  </Table>

  <BasicModal ref="deploymentModal" width="1000px" @emit-callback-fn="addCallbackFn">
    <template #content="{ data }">
      <NavTitle title="基本信息" showRightIcon class="navTitle" />
      <div class="deployment-content deployment-title deployment-grid deployment-content-bottom">
        <div class="deployment-info" v-for="(item, index) in deploymentList" :key="index">
          <div class="deployment-name">{{ item.name }}</div>
          <div class="deployment-description">
            <template v-if="item?.slot !== 'button'">
              {{ item.description || '--' }}
            </template>
            <div v-if="item?.slot === 'button'" class="deployment-description-button">
              <div class="deployment-description-button-left">{{ item.description || '--' }}</div>
              <div class="deployment-description-button-right">
                <a-button class="actionBtn" type="primary" ghost size="small" @click="handleContinue(data)">
                  继续
                </a-button>
                <a-button
                  v-if="data.taskInstanceStatus == TaskStatus.success"
                  class="actionBtn"
                  type="primary"
                  ghost
                  size="small"
                  @click="rollbackDeployment(data)"
                >
                  回滚
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <NavTitle title="工作负载" showRightIcon class="navTitle" />
      <div class="deployment-content-bottom">
        <Table
          ref="modalTableRef"
          :columns="deploymentColumns"
          :data="loadDeploymentData"
          :alert="false"
          bordered
          :showPagination="false"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
            <template v-if="column.dataIndex === 'status'">
              {{ podStatusMap[record.status as PodStatus]?.text }}
            </template>
            <template v-if="column.dataIndex === 'action'">
              <div class="table-operation">
                <a @click="handleDetail(record)">详情</a>
                <a @click="handleViewLog(record)">查看日志</a>
              </div>
            </template>
          </template>
        </Table>
      </div>
    </template>
  </BasicModal>

  <AppLogModal ref="appLogModalRef" @close-modal="closeModal" />
  <PodInfoDetailModal ref="podInfoDetailModalRef" title="详情-工作负载" />
</template>

<script setup lang="ts">
import PodInfoDetailModal from './podInfoDetailModal.vue';
import AppLogModal from './appLogModal.vue';
import { podStatusMap, taskStatusMap, deploymentProgressList } from '@/settings/commonSettings';
import { PodStatus, TaskStatus } from '@/enums/pipelineEnum';
import {
  getDeploymentUnitFun,
  getPodListDataFun,
  getDeployStrategyList,
  queryByPipelineInstanceCode,
  deploymentUnitContinue,
  deploymentUnitRollback,
} from '@/api/applicationManagement';
import { useApplicationStore } from '@/store/modules/app';
import { storeToRefs } from 'pinia';
import { message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { Modal } from 'ant-design-vue';
const counterStore = useApplicationStore();
const { componentData } = storeToRefs(counterStore);

const props = defineProps({
  environmentUuid: {
    type: [String, Number],
    required: true,
  },
});
const emits = defineEmits(['emitUpdateMyLineMsgList']);
const columns = [
  { dataIndex: 'deploymentVersion', title: '部署版本号', align: 'center' },
  { dataIndex: 'programVersion', title: '编排版本', align: 'center' },
  { dataIndex: 'deploymentName', title: '部署单', align: 'center' },
  { dataIndex: 'taskInstanceStatus', title: '部署状态', align: 'center' },
  { dataIndex: 'createTime', title: '创建时间', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const tableRef = ref<any>(null);
const modalTableRef = ref<any>(null);

watch(
  () => props.environmentUuid,
  (newVal) => {
    nextTick(() => {
      newVal && tableRef.value.refresh(true);
    });
  },
  {
    immediate: true,
  },
);

watch(
  () => componentData,
  () => {
    nextTick(() => {
      tableRef.value.refresh(true);
    });
  },
  {
    immediate: true,
  },
);

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      environmentUuid: props.environmentUuid,
      componentLabel: componentData.value.label,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  if (!props.environmentUuid) return;
  return await getDeploymentUnitFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res?.records || [],
    };
    return data;
  });
};
const deployStrategy = ref<any>([]);
const deploymentModal = ref<any>(null);
const podInfoDetailModalRef = ref<any>(null);
const appLogModalRef = ref<any>(null);
const deploymentList = ref([
  {
    name: '部署版本号',
    value: 'deploymentVersion',
    description: '',
  },
  {
    name: '编排版本',
    value: 'programVersion',
    description: '',
  },
  {
    name: '部署单',
    value: 'deploymentName',
    description: '',
  },
  {
    name: '目标副本',
    value: 'targetReplicas',
    description: '',
  },
  {
    name: '分批次数',
    value: 'batchCount',
    description: '',
  },
  {
    name: '部署策略',
    value: 'deploymentWay',
    description: '',
  },
  {
    name: '部署进度',
    value: 'deploymentProgress',
    description: '',
    slot: 'button',
  },
]);

const goToDetaile = async (record: any) => {
  await getDeployStrategyListFun();
  await upDateDetailInfo(record.pipelineInstanceCode);
  deploymentModal.value.showModal(record, '关闭');
};

// 更新部署单详情信息
const upDateDetailInfo = async (code: string) => {
  const data = await getDeploymentDetail(code);
  deploymentList.value = deploymentList.value.map((item) => {
    item.description = data[item.value];
    // 部署策略
    if (item.value === 'deploymentWay') {
      item.description = deployStrategy.value.find((v: any) => v.id == data.deploymentWay)?.text || '--';
    }
    // 部署进度
    if (item.value === 'deploymentProgress') {
      let str = deploymentProgressList.find((v: any) => v.dictValue == data.deploymentProgress)?.dictName || '--';
      item.description = str as string;
    }
    return item;
  });
};

const addCallbackFn = () => {
  deploymentModal.value.hideModal();
};

const deploymentColumns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'podName', title: 'pod信息', align: 'center' },
  { dataIndex: 'status', title: '运行状态', align: 'center' },
  { dataIndex: 'ready', title: '就绪状态', align: 'center' },
  { dataIndex: 'createTime', title: '创建时间', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

// 回滚
const rollbackDeployment = async (item: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要执行回滚操作吗？`),
    async onOk() {
      await deploymentUnitRollback(item.id).then(() => {
        upDateDetailInfo(item.pipelineInstanceCode);
        updateList();
        message.success('操作成功');
      });
    },
    onCancel() {},
  });
};

// 继续
const handleContinue = async (item: any) => {
  await deploymentUnitContinue(item.id).then(() => {
    upDateDetailInfo(item.pipelineInstanceCode);
    updateList();
    message.success('操作成功');
  });
};

// 刷新数据
const updateList = () => {
  loadDeploymentData();
  tableRef.value.refresh(true);
  modalTableRef.value.refresh(true);
  emits('emitUpdateMyLineMsgList');
};

const loadDeploymentData = async () => {
  if (!props.environmentUuid) return;
  return await getPodListDataFun({
    environmentUuid: props.environmentUuid,
    componentLabel: componentData.value.label,
  }).then((res) => {
    return res;
  });
};

const handleDetail = (obj: any) => {
  podInfoDetailModalRef.value.onOpen(obj);
};

//查看日志
const handleViewLog = async (obj: any) => {
  if (!props.environmentUuid) return;
  appLogModalRef.value.showModal({ envId: props.environmentUuid, podName: obj.podName });
};

const closeModal = () => {};

// 获取部署策略枚举值
const getDeployStrategyListFun = async () => {
  return await getDeployStrategyList().then((res) => {
    deployStrategy.value = res;
  });
};

// 获取部署单详情
const getDeploymentDetail = async (code: string) => {
  return await queryByPipelineInstanceCode(code).then((res) => {
    return res;
  });
};
</script>

<style scoped lang="less">
.deployment-grid {
  display: flex;
  flex-wrap: wrap;
}
.deployment-title {
  border-top: 1px solid #ecf3fb;
  border-left: 1px solid #ecf3fb;
  border-radius: 4px;
}
.deployment-content-bottom {
  margin-bottom: 24px;
}
.deployment-content {
  // margin: 0 0 24px 0;

  .deployment-info {
    display: flex;
    align-items: center;
    width: 50%;
    border-bottom: 1px solid #ecf3fb;
    border-right: 1px solid #ecf3fb;

    .deployment-name {
      max-width: 180px;
      flex: 3;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 20px;
      background: #f9faf9;
      box-shadow: 1px 0px 0px 0px rgba(236, 243, 251, 1);
      border-radius: 4px 0px 0px 0px;
      font-size: 14px;
      color: #666666;
      font-weight: 400;
    }
    .deployment-description {
      flex: 7;
      max-width: 320px;
      text-align: left;
      width: 100%;
      padding: 20px;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.8);
      letter-spacing: 0;
      font-weight: 400;
      position: relative;

      &-text {
        color: #2590ff;
        margin-left: 16px;
        cursor: pointer;
      }

      &-button {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        &-left {
          flex: 2;
        }
        &-right {
          display: flex;
          justify-content: space-between;
          align-items: center;
          button {
            margin-right: 8px;
          }
        }
      }

      .icon-container {
        position: absolute;
        top: 5px;
        right: 8px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
}
.navTitle {
  margin-bottom: 20px;
}
.tag-class {
  display: inline-flex;
  justify-content: center;
  align-items: center;
}
</style>
